Imports DaveSexton.DocProject.DocSites

Partial Public Class DocSiteBrowseIndex
	Inherits System.Web.UI.Page

	Public Property KeywordFirstLetter() As Nullable(Of Char)
		Get
			Return CType(ViewState("_$KeywordFirstLetter"), Nullable(Of Char))
		End Get
		Set(ByVal value As Nullable(Of Char))
			ViewState("_$KeywordFirstLetter") = value

			letterLabel.Visible = value.HasValue
		End Set
	End Property

	Protected ReadOnly Property KeywordFirstLetterLabelText() As String
		Get
			If KeywordFirstLetter.HasValue Then
				Return Char.ToUpper(KeywordFirstLetter.Value).ToString()
			Else
				Return CType(GetLocalResourceObject("letterLabel.NoLetter"), String)
			End If
		End Get
	End Property

	Public ReadOnly Property Keywords() As List(Of String)
		Get
			Dim _keywords As List(Of String) = CType(ViewState("_$Keywords"), List(Of String))

			If _keywords Is Nothing Then
				_keywords = New List(Of String)()
				ViewState("_$Keywords") = _keywords
			End If

			Return _keywords
		End Get
	End Property

	Public ReadOnly Property DocSiteFramePath() As String
		Get
			Return DocSiteManager.Settings.DocSiteFramePath
		End Get
	End Property

	Public ReadOnly Property ShowSearchButton() As Boolean
		Get
			Return DocSiteManager.Settings.SearchEnabled OrElse User.Identity.IsAuthenticated
		End Get
	End Property

	Private keywordPosition, entryPosition As Integer

	Private Sub UpdateKeywordsList()
		Dim _keywords As List(Of String) = Keywords

		If _keywords.Count > 0 Then
			userKeywordsRepeater.DataBind()
			userKeywordsRepeater.Visible = True

			' # Occurrences and Weight only have meaningful data when one keyword is selected for the filter
			keywordEntriesGridView.Columns(3).Visible = (_keywords.Count = 1)
			keywordEntriesGridView.Columns(4).Visible = (_keywords.Count = 1)

			keywordEntriesGridView.DataBind()
			keywordEntriesPanel.Visible = Not keywordsListPanel.Visible
		Else
			userKeywordsRepeater.Visible = False
			keywordEntriesPanel.Visible = False
		End If
	End Sub

	Protected Function IsKeywordIndexed(ByVal _keyword As String) As Boolean
		Return DaveSexton.DocProject.DocSites.DocSiteSearch.IsKeywordIndexed(_keyword)
	End Function

	Protected Function GetNextEntryPosition() As Integer
		entryPosition += 1
		Return entryPosition + (keywordEntriesGridView.PageIndex * keywordEntriesGridView.PageSize)
	End Function

	Protected Function GetNextKeywordPosition() As Integer
		keywordPosition += 1
		Return keywordPosition + (keywordsGridView.PageIndex * keywordsGridView.PageSize)
	End Function

	Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
		If Not User.Identity.IsAuthenticated AndAlso Not DocSiteManager.Settings.BrowseIndexEnabled Then
			Response.Redirect(DocSiteManager.Settings.DocSiteFramePath)
		End If

		ScriptManager.GetCurrent(Page).AsyncPostBackTimeout = DocSiteManager.Settings.CreateIndexRefreshTimeout

		MyBase.OnInit(e)
	End Sub

	Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
		MyBase.OnLoad(e)

		If Not Page.IsPostBack Then
			Dim query As String = Request.QueryString("q")

			If Not String.IsNullOrEmpty(query) Then
				Dim factory As New QueryExpressionFactory()
				factory.DefaultOperator = CChar("&")
				factory.SplitQueryCharacters = DaveSexton.DocProject.DocSites.DocSiteSearch.DefaultSearchProvider.SplitQueryCharacters
				factory.IgnoredWords = DocSiteManager.Settings.SearchExcludedKeywords.Split(New Char() {CChar(",")}, StringSplitOptions.RemoveEmptyEntries)
				factory.MinimumKeywordLength = DocSiteManager.Settings.SearchMinimumKeywordLength
				factory.Optimize = False

				Dim expression As QueryExpression = factory.CreateExpression(query)

				If Not TypeOf expression Is EmptyQueryExpression Then
					expression.Evaluate(AddressOf AddTermsToKeywordsList)
				End If

				' The index must always be created when a query is specified otherwise it will be generated 
				' automatically _after_ the keywords are rendered, which means they'll all appear in "red".
				DaveSexton.DocProject.DocSites.DocSiteSearch.EnsureIndex()

				keywordsListPanel.Visible = False
				KeywordFirstLetter = Nothing
			End If
		End If
	End Sub

	Private Sub AddTermsToKeywordsList(ByVal expr As QueryExpression)
		If TypeOf expr Is TermQueryExpression Then
			Dim term As TermQueryExpression = CType(expr, TermQueryExpression)

			If Not Keywords.Contains(term.Term) Then
				Keywords.Add(term.Term)
			End If
		End If
	End Sub

	Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
		MyBase.OnPreRender(e)

		Dim firstLetter As Nullable(Of Char) = KeywordFirstLetter

		If firstLetter.HasValue Then
			keywordsDataSource.SelectParameters("firstLetter").DefaultValue = firstLetter.ToString()
			keywordEntriesPanel.Visible = False
			keywordsListPanel.Visible = True
		End If

		UpdateKeywordsList()

		Dim indexCreated As Boolean = DaveSexton.DocProject.DocSites.DocSiteSearch.IndexCreated

		keywordsCreateIndexProgressPlaceholder.Visible = Not indexCreated
		keywordsPleaesWaitProgressPlaceholder.Visible = indexCreated
	End Sub

	Protected Sub allKeywordsLinkButton_Click(ByVal sender As Object, ByVal e As EventArgs)
		keywordsDataSource.SelectParameters("firstLetter").DefaultValue = Nothing
		KeywordFirstLetter = Nothing
		keywordEntriesPanel.Visible = False
		keywordsListPanel.Visible = True
		keywordsGridView.PageIndex = 0
	End Sub

	Protected Sub letterBar_LetterClick(ByVal sender As Object, ByVal e As CommandEventArgs)
		KeywordFirstLetter = e.CommandName(0)
		keywordsGridView.PageIndex = 0
		letterLabel.DataBind()
	End Sub

	Protected Sub keywordsLinkButton_Click(ByVal sender As Object, ByVal e As EventArgs)
		keywordsListPanel.Visible = False
		KeywordFirstLetter = Nothing
	End Sub

	Protected Sub keyword_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
		If String.Equals(e.CommandName, "Keyword", StringComparison.OrdinalIgnoreCase) Then
			Dim word As String = CType(e.CommandArgument, String)

			If Not String.IsNullOrEmpty(word) Then
				If Not Keywords.Contains(word) Then
					Keywords.Add(word)
				End If

				keywordsListPanel.Visible = False
				KeywordFirstLetter = Nothing
			End If
		End If
	End Sub

	Protected Sub removeKeywordImageButton_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
		If String.Equals(e.CommandName, "Remove", StringComparison.OrdinalIgnoreCase) Then
			Dim word As String = CType(e.CommandArgument, String)

			If Not String.IsNullOrEmpty(word) Then
				Keywords.Remove(word)

				keywordsListPanel.Visible = False
				KeywordFirstLetter = Nothing
			End If
		End If
	End Sub

	Protected Sub keywordEntriesDataSource_Selecting(ByVal sender As Object, ByVal e As ObjectDataSourceSelectingEventArgs)
		e.InputParameters.Add("keywords", Keywords.ToArray())
	End Sub

	Protected Sub searchImageButton_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
		DocSiteNavigator.NavigateToSearchResults(String.Join(" ", Keywords.ToArray()))
	End Sub
End Class